package com.example.docking.controller;

import com.example.docking.dao.jindie.GenericDataItem;
import com.example.docking.dao.jindie.ResponseData;
import com.example.docking.dao.jindie.request.CommonOperateDao;
import com.example.docking.dao.jindie.request.MoTaskBillRequest;
import com.example.docking.dao.jindie.response.*;
import com.example.docking.dao.jindie.response.customFiel.CustomField;
import com.example.docking.dao.jindie.response.customFiel.CustomFieldData;
import com.example.docking.dao.jindie.response.motaskbill.SubMaterialEntity;
import com.example.docking.dao.jingxin.putJXRaskbillDao;
import com.example.docking.httpJX.HttpUrlConnectionExample;
import com.example.docking.service.impl.*;
import com.example.docking.util.Constants;
import com.example.docking.util.TimeRangeMap;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.smecloud.apigw.model.ApiResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class SalesOrderController {
    private static final Logger logger = LoggerFactory.getLogger(SalesOrderController.class);
    private DataServiceImpl Service = new DataServiceImpl();
    private Gson gson = new Gson();
    private HashMap<String, String> map = new HashMap<>();

    /**
     * @MethodName selectSalesOrder
     * @Parameters 定时循环获取销售订单数据  获取未审核的数据
     * @Author zhanghuiping
     * @Date 2025 - 05 - 06 02:03:14
     */
    public List<SalesOrderData> selectSalesOrder() {
        // 设置分页参数
        int page = 1; // 初始页码
        int pageSize = 10; // 每页记录数
        map.put("page", String.valueOf(page));
        map.put("page_size", String.valueOf(pageSize));
        TimeRangeMap timeRangeMap = new TimeRangeMap();
        map.put("create_start_time", timeRangeMap.getDayStartTime()); //    创建时间-开始时间的时间戳(毫秒)
        map.put("create_end_time", timeRangeMap.getDayEndTime()); //  	创建时间-结束时间的时间戳(毫秒)
        map.put("bill_status", "Z");//单据状态（所有：“”，已审核：“C”，未审核：“Z”）
        List<SalesOrderData> allSaleData = null;
        try {
            ApiResult SalesOrderDataResult = Service.SelectDataList(Constants.SAL_ORDER, map, "");

            Type SaleDataType = new TypeToken<ResponseData<GenericDataItem<SalesOrderData>>>() {
            }.getType();
            ResponseData<GenericDataItem<SalesOrderData>> responseSaleData = gson.fromJson(SalesOrderDataResult.getBody(), SaleDataType);
            logger.info("查询订单返回结果：" + responseSaleData);
            GenericDataItem<SalesOrderData> genericDataItemSale = responseSaleData.getData();
            // 解析分页信息
            String count = genericDataItemSale.getCount();
            int countNum = Integer.valueOf(count);
            int Pagesum = pageSize;
            List<SalesOrderData> SaleData = genericDataItemSale.getRows();

            allSaleData = new ArrayList<>(SaleData);
            // 如果不是最后一页，继续获取下一页数据
            while (Pagesum < countNum) {
                page++;
                map.put("page", String.valueOf(page));
                SalesOrderDataResult = Service.SelectDataList(Constants.SAL_ORDER, map, "");
                responseSaleData = gson.fromJson(SalesOrderDataResult.getBody(), SaleDataType);
                genericDataItemSale = responseSaleData.getData();
                SaleData = genericDataItemSale.getRows();
                allSaleData.addAll(SaleData);
                Pagesum = (pageSize * page);
            }

            logger.info("销售订单:allSaleData: {}", allSaleData);

        } catch (Exception ex) {
            logger.error("查询销售订单：Error occurred while selecting sales order", ex);
            throw new RuntimeException(ex);
        }

        return allSaleData;
    }

    /**
     * @ClassName SalesOrderController
     * @Description 需求：
     * 要求，销售单填写完成后，ERP要根据商品属性，属性是“半成品或产成品或自制件＂，则自动生成＂生产任务单＂，
     * 然后将＂生产任务单＂传输给敬信，字段：生产任务单号，生产设备的物料号，生产设备名称，数量，单位，项目号
     * @Author zhanghuiping
     * @Date 2025 - 04 - 08 05:43:46
     */
    public ArrayList<MoTaskBillRequest> getSelfMaterial(List<SalesOrderData> allSaleData) {
        int page = 1; // 初始页码
        int pageSize = 10; // 每页记录数
        map.put("page", String.valueOf(page));
        map.put("page_size", String.valueOf(pageSize));
        ArrayList<MoTaskBillRequest> moTaskBillRequest = new ArrayList<>();
        SupplierServiceImpl.SUPPLIERDATA = null;
        for (SalesOrderData salesOrder : allSaleData) {
            //根据销售订单生成生产任务单
            String id = salesOrder.getId();
            map.put("id", id);
            // 需要自制的 销售订单：List<SalesOrderData>
            //根据销售订单获取商品分录：
            ApiResult detailOrderSale = null;

            try {
                //根据id产讯销售详情获取详情数据
                detailOrderSale = Service.SelectDataDetail(Constants.SAL_ORDER_DETAIL, map, "");

                Type detailDataType = new TypeToken<ResponseData<SalOrderDetailData>>() {
                }.getType();
                ResponseData<SalOrderDetailData> detailOrderSaleData = gson.fromJson(detailOrderSale.getBody(), detailDataType);
                if (detailOrderSaleData.getErrcode() == 0) {
                    SalOrderDetailData salOrderDetailData = detailOrderSaleData.getData();

                    List<MaterialEntity> material_entity = salOrderDetailData.getMaterial_entity();
//                    List<MaterialEntity> Material1 = new ArrayList<>(); //一个生产任务多个商品---现在的逻辑是一个生产任务一个生产工单
                    //存储非自制的商品 materialEntityList 直接生成采购申请订单
                    List<MaterialEntity> materialEntityList = new ArrayList<>();
                    for (MaterialEntity materiaElntity : material_entity) {
                        //属性是“半成品或产成品或自制件＂
                        //自制的商品，一个商品对应一个生产工单
                        String idmateria = materiaElntity.getMaterial_id();
                        String[] ids = new String[1];
                        ids[0] = idmateria;
                        // 将数组转换为逗号分隔的字符串
                        String idsParam = String.join(",", ids);
                        map = new HashMap<>();
                        map.put("page", String.valueOf(page));
                        map.put("page_size", String.valueOf(pageSize));
                        map.put("ids", idsParam);
                        //根据销售订单获取商品分录：因为详情里面没有只能查列表字段是否有自制
                        ApiResult detailMateria = Service.SelectDataList(Constants.MATERIAL_PATH, map, "");
                        Type MateriaDataType = new TypeToken<ResponseData<GenericDataItem<MaterialData>>>() {
                        }.getType();
                        ResponseData<GenericDataItem<MaterialData>> detailMateriaData = gson.fromJson(detailMateria.getBody(), MateriaDataType);
                        GenericDataItem<MaterialData> genericDataItemMaterial = detailMateriaData.getData();
                        List<MaterialData> materialData = genericDataItemMaterial.getRows();

                        for (MaterialData materialData1 : materialData) {
                            logger.info("查询回来的：materialData1: {}", materialData1);
                            String is_self_restraint = materialData1.getIs_self_restraint();
                            if ("true".equals(is_self_restraint)) {
                                //Message: proto: (line 1:1706): invalid value for string type: 1 不能直接复制 不然报错 排除不出来
                                //添加商品id 到生产任务单
                                MaterialEntity materialEntity2 = new MaterialEntity();
                                //生产任务单数据  qty  数量
                                materialEntity2.setQty(materiaElntity.getBase_qty());
                                //plan_commit_date	string	true	计划开工日期（格式：2019-01-01） 单据日期
                                materialEntity2.setPlan_commit_date(salOrderDetailData.getBill_date());
                                //plan_finish_date	string	true	计划完工日期（格式：2019-01-01）单据结算日期
                                materialEntity2.setPlan_finish_date(salOrderDetailData.getDue_date());
                                //商品id
                                materialEntity2.setMaterial_id(materiaElntity.getMaterial_id());
                                materialEntity2.setMaterial_name(materiaElntity.getMaterial_name());
                                materialEntity2.setMaterial_number(materiaElntity.getMaterial_number());
                                //单位id
                                materialEntity2.setUnit_id(materiaElntity.getUnit_id());
                                materialEntity2.setUnit_name(materiaElntity.getUnit_name());
                                materialEntity2.setUnit_number(materiaElntity.getUnit_number());
                                //材料分录  第一步保存生产任务单到金蝶的时候预设的材料分录
                                List<SubMaterialEntity> subMaterialEntities = new ArrayList<>();
                                SubMaterialEntity subMaterialEntity2 = new SubMaterialEntity();
                                //den_qty_scrap	string	true	产品产量（分母）
                                //num_qty_scrap	string	true	材料用量（分子）
                                //sub_material_id	string	true	物料编码ID
                                //sub_qty	number	true	计划投料数
                                //sub_unit_id	string	true	单位(M)ID

                                subMaterialEntity2.setSub_material_id("2358117042021819392");//模拟材料id
                                subMaterialEntity2.setSub_unit_id("5");
                                subMaterialEntity2.setDen_qty_scrap("1");
                                subMaterialEntity2.setNum_qty_scrap("1");
                                subMaterialEntity2.setSub_qty(1);
                                subMaterialEntities.add(subMaterialEntity2);
                                materialEntity2.setSub_material_entity(subMaterialEntities);


                                List<MaterialEntity> Material1 = new ArrayList<>();
                                Material1.add(materialEntity2);
                                MoTaskBillRequest moTaskBillRequest1 = new MoTaskBillRequest();
                                moTaskBillRequest1.setEmp_id(salesOrder.getEmp_id());
                                moTaskBillRequest1.setEmp_name(salesOrder.getEmp_name());
                                moTaskBillRequest1.setEmp_number(salesOrder.getEmp_number());
                                moTaskBillRequest1.setMaterial_entity(Material1);
                                //源单销售订单单号
                                moTaskBillRequest1.setSrc_bill_no(salOrderDetailData.getBill_no());
                                //源单销售订单 类型
                                moTaskBillRequest1.setSrc_bill_type_id(Constants.SAL_BILL_ORDER);
                                //源单销售订单 id
                                moTaskBillRequest1.setSrc_inter_id(salOrderDetailData.getId());
                                moTaskBillRequest1.setRemark(salOrderDetailData.getBill_no());
                                moTaskBillRequest1.setEmp_id(salesOrder.getEmp_id());
                                //自定义字段  查询销售订单的 自定义字段
                                Map<String, String> customField = salOrderDetailData.getCustom_field();
                                CustomFieldServiceImpl customFieldServiceImpl = new CustomFieldServiceImpl();
                                ResponseData<CustomFieldData> responseData = customFieldServiceImpl.selectMaterial(Constants.SAL_BILL_ORDER);
                                String mapkey = "";
                                if (responseData.getErrcode() == 0) {
                                    CustomFieldData customFieldData = responseData.getData();
                                    List<CustomField> head = customFieldData.getHead();
                                    CustomField customField1 = head.get(0);
                                    mapkey = customField1.getNumber();
                                }
                                String Value = customField.get(mapkey);
                                //保存到销售订单的 自定义字段
                                ResponseData<CustomFieldData> responseData1 = customFieldServiceImpl.selectMaterial(Constants.MO_TASK_BILL_TYPE);
                                String mapkey1 = "";
                                String mapkey2 = "";
                                if (responseData1.getErrcode() == 0) {
                                    CustomFieldData customFieldData = responseData1.getData();
                                    if (customFieldData != null) {
                                        List<CustomField> head = customFieldData.getHead();
                                        if (head.size() > 0) {
                                            for (CustomField customField1 : head) {
                                                if ("项目名称".equals(customField1.getDisplay_name())) {
                                                    mapkey1 = customField1.getNumber();
                                                }
                                                if ("交货日期".equals(customField1.getDisplay_name())) {
                                                    mapkey2 = customField1.getNumber();
                                                }
                                            }
                                        }

                                    }
                                }
                                Map<String, String> customField1 = new HashMap<>();
                                if (mapkey1 != null && !mapkey1.equals("")) {
                                    customField1.put(mapkey1, Value);
                                }
                                //交付日期--- 自定义字段
                                String date1 = materiaElntity.getDelivery_date();
                                if (mapkey2 != null && !mapkey2.equals("")) {
                                    customField1.put(mapkey2, date1);
                                }
                                moTaskBillRequest1.setCustom_field(customField1);
                                moTaskBillRequest.add(moTaskBillRequest1);

                            } else {
                                //非自制的直接生成采购申请单
                                MaterialEntity materialEntity3 = new MaterialEntity();
                                materialEntity3.setMaterial_id(materiaElntity.getMaterial_id());
                                materialEntity3.setUnit_id(materiaElntity.getUnit_id());
                                materialEntity3.setApply_qty(materiaElntity.getQty());
                                materialEntity3.setDelivery_date(materiaElntity.getDelivery_date());
                                materialEntityList.add(materialEntity3);
                            }
                        }


                    }
                    logger.info("所有生成的任务单号：" + gson.toJson(moTaskBillRequest));

                    //生成采购申请单 ---  销售非自制
                    if (materialEntityList.size() > 0) {
                        logger.info("生成采购申请单------非自制");
                        PurRequestServiceImpl purRequestServiceImpl = new PurRequestServiceImpl();
                        ResponseData responseDataresult = purRequestServiceImpl.InsertPurRequestSCDD(salesOrder.getEmp_id(), salesOrder.getBill_no(), materialEntityList);
                        logger.info(responseDataresult.toString());
                    }

                } else {
                    logger.error("Error occurred while getting order details. Errcode: {}, Description: {}", detailOrderSaleData.getErrcode(), detailOrderSaleData.getDescription());
                    throw new RuntimeException(detailOrderSaleData.getErrcode() + ":" + detailOrderSaleData.getDescription());
                }

            } catch (Exception e) {
                logger.error("Error occurred while getting self material", e);
                throw new RuntimeException(e);
            }

        }
        return moTaskBillRequest;
    }

    /**
     * @ClassName SalesOrderController
     * @Description 需求：根据crm 销售订单 生成生产任务工单
     * 暂定 从 金蝶销售订单获取 保存到金蝶 ===  推送给敬信
     * @Author zhanghuiping
     * @Date 2025 - 04 - 09 02:09:35
     */
    public ResponseData insertRaskGetBySalesOrder() {
        logger.info("监控销售订单数据");
        SalesOrderController controller = new SalesOrderController();
        //先推送敬信成功了全部成功了 在保存  多条推送都成功
        ResponseData responseData = new ResponseData();
        try {
            //1.定时任务循环获取销售订单
            List<SalesOrderData> listSales = controller.selectSalesOrder();

            //过滤掉已经生成生产任务单的销售订单
            List<MoTaskbillDetailData> moTaskbillDetailDatas = selectUnauditedTaskOrders();
            moTaskbillDetailDatas.removeIf(moTaskbillDetailData -> StringUtils.isBlank(moTaskbillDetailData.getRemark()));
            //moTaskbillDetailDatas按remark分组
            Map<String, List<MoTaskbillDetailData>> collect = moTaskbillDetailDatas.stream().collect(Collectors.groupingBy(MoTaskbillDetailData::getRemark));
            listSales.removeIf(salesOrderData -> collect.containsKey(salesOrderData.getBill_no()));
            logger.info("过滤掉已经生成生产任务单的销售订单后，剩余的销售订单数量：" + listSales.size());
            if (listSales.size() == 0) {
                return responseData;
            }

            //2.判断销售订单需要自制的部分
            ArrayList<MoTaskBillRequest> moTaskBillRequests = controller.getSelfMaterial(listSales);
            DataServiceImpl Service = new DataServiceImpl();
            MoTaskbillServiceImpl moTaskbillService = new MoTaskbillServiceImpl();
            //3.先新增有生产任务单号 再推送给敬信
            ArrayList<MoTaskBillRequest> moTaskBillRequestInsert = moTaskbillService.InsertMoTaskbillByERP(Service, moTaskBillRequests);
            if (moTaskBillRequestInsert.size() > 0) {
                //4.保存成功审核一下 销售数据，下次不在查询
                controller.auditSaleOrder(listSales);
                HttpUrlConnectionExample HttpExample = new HttpUrlConnectionExample();
                //5.保存携带销售订单编号的生产任务单  生产任务单是 一个自制的的商品对应一个生产任务单
                List<putJXRaskbillDao> putJXRaskDaoList = new ArrayList<>();
                for (MoTaskBillRequest moTaskBillRequest : moTaskBillRequests) {
                    putJXRaskbillDao putJXRaskDao = new putJXRaskbillDao();
                    putJXRaskDao.setTask_no(moTaskBillRequest.getBill_no());
                    putJXRaskDao.setEmp(moTaskBillRequest.getEmp_name());
                    putJXRaskDao.setTrans_type_id(moTaskBillRequest.getTrans_type_id());
                    MaterialEntity materialEntity = moTaskBillRequest.getMaterial_entity().get(0);
                    putJXRaskDao.setMaterialCode(materialEntity.getMaterial_number());//图令号
                    putJXRaskDao.setMaterialName(materialEntity.getMaterial_name());
                    putJXRaskDao.setMaterialNumber(String.valueOf(materialEntity.getQty()));//金蝶id
                    putJXRaskDao.setUnit(materialEntity.getUnit_name());
                    putJXRaskDao.setPlan_commit_date(materialEntity.getPlan_commit_date());
                    putJXRaskDao.setPlan_finish_date(materialEntity.getPlan_finish_date());
                    putJXRaskDao.setOrder_no(moTaskBillRequest.getSrc_bill_no());
                    Map<String, String> CustFiled = moTaskBillRequest.getCustom_field();
                    //保存到销售订单的 自定义字段
                    CustomFieldServiceImpl customFieldServiceImpl = new CustomFieldServiceImpl();
                    ResponseData<CustomFieldData> responseData1 = customFieldServiceImpl.selectMaterial(Constants.MO_TASK_BILL_TYPE);
                    String mapkey1 = "";
                    String mapkey2 = "";
                    if (responseData1.getErrcode() == 0) {
                        CustomFieldData customFieldData = responseData1.getData();
                        if (customFieldData != null) {
                            List<CustomField> head = customFieldData.getHead();
                            if (head.size() > 0) {
                                for (CustomField customField1 : head) {
                                    if ("项目名称".equals(customField1.getDisplay_name())) {
                                        mapkey1 = customField1.getNumber();
                                    }
                                    if ("交货日期".equals(customField1.getDisplay_name())) {
                                        mapkey2 = customField1.getNumber();
                                    }
                                }
                            }

                        }
                    }
                    //推送项目名称
                    if (mapkey1 != null && !mapkey1.equals("")) {
                        putJXRaskDao.setOrder_name(CustFiled.get(mapkey1));
                    }
                    //推送交货日期
                    if (mapkey2 != null && !mapkey2.equals("")) {
                        putJXRaskDao.setOrder_date(CustFiled.get(mapkey2));
                    }
                    putJXRaskDaoList.add(putJXRaskDao);
                }
                logger.info("推送到敬信数据 putJXRaskDaoList: {}", gson.toJson(putJXRaskDaoList));
                String response = HttpExample.sendRequestApplyProduceOrder(gson.toJson(putJXRaskDaoList));
                if (response == null || "".equals(response)) {
                    logger.info("销售订单时-生产任务单==》推送失败：再次推送");
                } else if (response.contains("集成成功")) {
                    logger.info("销售订单时-生产任务单==》推送到敬信成功返回：response: {}", response);
                    //6.保存成功审核一下 销售数据，下次不在查询Z
                    controller.auditTaskOrder(moTaskBillRequests);
                } else {
                    logger.info("销售订单时-生产任务单==》1：再次推送");
                    logger.info("推送失败原因1：response: {}", response);
                }
            } else {
                logger.info("没有数据需要推送敬信--新增和审核");
            }


        } catch (Exception e) {
            logger.error("Error occurred while inserting task based on sales order", e);
            throw new RuntimeException(e);
        }
        return responseData;
    }

    /**
     * @MethodName auditSaleOrder
     * @Parameters 审核销售订单  ---销售订单生成生产任务单完成后自动审核成功
     * @Author zhanghuiping
     * @Date 2025 - 05 - 06 01:59:50
     */
    private void auditSaleOrder(List<SalesOrderData> listSales) {
        List<String> ids = new ArrayList<>();
        for (SalesOrderData salesOrderData : listSales) {
            ids.add(salesOrderData.getId());
        }
        logger.info("销售订单审核的ids: {}", ids);
        CommonOperateDao commonOperateDao = new CommonOperateDao();
        commonOperateDao.setEntity_number(Constants.SAL_BILL_ORDER);
        commonOperateDao.setIds(ids);
        commonOperateDao.setOperate_type(Constants.AUDIT);
        try {
            ApiResult auditData = Service.SelectDataAudit(Constants.COMMON_OPERATE, map, commonOperateDao);
            Type type1 = new TypeToken<ResponseData<SaveData>>() {
            }.getType();
            ResponseData<SaveData> response = gson.fromJson(auditData.getBody(), type1);
            if (response.getErrcode() == 0) {
                logger.info("审核销售订单成功");
                logger.info("审核销售订单Code: {}", response.getErrcode());
                logger.info("审核销售订单Message: {}", response.getDescription());
                logger.info("审核销售订单data: {}", response.getData());
            } else {
                logger.error("审核销售订单失败. Errcode: {}, Description: {}", response.getErrcode(), response.getDescription());
                throw new RuntimeException(response.getErrcode() + ":" + response.getDescription());
            }
        } catch (Exception e) {
            logger.error("Error occurred while auditing sales order", e);
            throw new RuntimeException(e);
        }

    }

    /**
     * @MethodName auditTaskOrder
     * @Parameters 审核生产任务单
     * @Author zhanghuiping
     * @Date 2025 - 05 - 06 02:00:54
     */
    private void auditTaskOrder(List<MoTaskBillRequest> moTaskBillRequests) {
        List<String> ids = new ArrayList<>();
        for (MoTaskBillRequest moTaskBillRequest : moTaskBillRequests) {
            ids.add(moTaskBillRequest.getId());
        }
        logger.info("生产任务单审核的ids: {}", ids);
        CommonOperateDao commonOperateDao = new CommonOperateDao();
        commonOperateDao.setEntity_number(Constants.MO_TASK_BILL_TYPE);
        commonOperateDao.setIds(ids);
        commonOperateDao.setOperate_type(Constants.AUDIT);
        try {
            ApiResult auditData = Service.SelectDataAudit(Constants.COMMON_OPERATE, map, commonOperateDao);
            Type type1 = new TypeToken<ResponseData<SaveData>>() {
            }.getType();
            ResponseData<SaveData> response = gson.fromJson(auditData.getBody(), type1);
            if (response.getErrcode() == 0) {
                logger.info("审核生产任务成功");
                logger.info("审核生产任务单Code: {}", response.getErrcode());
                logger.info("审核生产任务单Message: {}", response.getDescription());
                logger.info("审核生产任务单data: {}", response.getData());
            } else {
                logger.error("审核生产任务单失败. Errcode: {}, Description: {}", response.getErrcode(), response.getDescription());
                throw new RuntimeException(response.getErrcode() + ":" + response.getDescription());
            }
        } catch (Exception e) {
            logger.error("Error occurred while auditing sales order", e);
            throw new RuntimeException(e);
        }

    }

    /**
     * @MethodName selectTaskillOrder
     * @Parameters 查询生产任务单 获取未审核的数据
     * @Author zhanghuiping
     * @Date 2025 - 05 - 06 02:01:30
     */
    public ArrayList<MoTaskBillRequest> selectTaskillOrder() {
        ArrayList<MoTaskBillRequest> moTaskBillRequestInsert = new ArrayList<>();
        // 设置分页参数
        int page = 1; // 初始页码
        int pageSize = 10; // 每页记录数
        map.put("page", String.valueOf(page));
        map.put("page_size", String.valueOf(pageSize));
        TimeRangeMap timeRangeMap = new TimeRangeMap();
        map.put("modify_start_time", timeRangeMap.getDayStartTime()); //    创建时间-开始时间的时间戳(毫秒)
        map.put("modify_end_time", timeRangeMap.getDayEndTime()); //  	创建时间-结束时间的时间戳(毫秒)
        map.put("bill_status", "Z");//单据状态（所有：“”，已审核：“C”，未审核：“Z”）
        map.put("start_time", timeRangeMap.getDayStartTime());
        try {
            ApiResult DataResult = Service.SelectDataList(Constants.MO_TASKBILL, map, "");

            Type SaleDataType = new TypeToken<ResponseData<GenericDataItem<MoTaskbillData>>>() {
            }.getType();
            ResponseData<GenericDataItem<MoTaskbillData>> responseSaleData = gson.fromJson(DataResult.getBody(), SaleDataType);
            GenericDataItem<MoTaskbillData> genericDataItem = responseSaleData.getData();
            // 解析分页信息
            String count = genericDataItem.getCount();
            int countNum = Integer.valueOf(count);
            int Pagesum = pageSize;
            List<MoTaskbillData> Data = genericDataItem.getRows();
            for (MoTaskbillData moTaskbillData : Data) {
                MoTaskBillRequest moTaskBillRequest = new MoTaskBillRequest();
                moTaskBillRequest.setId(moTaskbillData.getId());
                moTaskBillRequest.setBill_no(moTaskbillData.getBill_no());
                moTaskBillRequest.setEmp_id(moTaskbillData.getEmp_id());
                moTaskBillRequest.setEmp_number(moTaskbillData.getEmpid_number());
                moTaskBillRequest.setEmp_name(moTaskbillData.getEmp_name());
                moTaskBillRequestInsert.add(moTaskBillRequest);
            }
            // 如果不是最后一页，继续获取下一页数据
            while (Pagesum < countNum) {
                page++;
                map.put("page", String.valueOf(page));
                DataResult = Service.SelectDataList(Constants.MO_TASKBILL, map, "");
                responseSaleData = gson.fromJson(DataResult.getBody(), SaleDataType);
                genericDataItem = responseSaleData.getData();
                Data = genericDataItem.getRows();
                for (MoTaskbillData moTaskbillData : Data) {
                    MoTaskBillRequest moTaskBillRequest = new MoTaskBillRequest();
                    moTaskBillRequest.setId(moTaskbillData.getId());
                    moTaskBillRequest.setBill_no(moTaskbillData.getBill_no());
                    moTaskBillRequest.setEmp_id(moTaskbillData.getEmp_id());
                    moTaskBillRequest.setEmp_number(moTaskbillData.getEmpid_number());
                    moTaskBillRequest.setEmp_name(moTaskbillData.getEmp_name());
                    moTaskBillRequestInsert.add(moTaskBillRequest);
                }
                Pagesum = (pageSize * page);
            }

            logger.info("生产任务单:allSaleData: {}", moTaskBillRequestInsert);

            for (MoTaskBillRequest moTaskbillData : moTaskBillRequestInsert) {
                HashMap<String, String> map1 = new HashMap<>();
                map1.put("id", moTaskbillData.getId());
                map1.put("page", "1");
                map1.put("page_size", "10");
                ApiResult DataResult1 = Service.SelectDataDetail(Constants.MO_TASKBILL_DETAIL, map1, "");

                Type SaleDataType1 = new TypeToken<ResponseData<MoTaskbillDetailData>>() {
                }.getType();
                ResponseData<MoTaskbillDetailData> responseSaleData1 = gson.fromJson(DataResult1.getBody(), SaleDataType1);
                if (responseSaleData1.getErrcode() == 0) {
                    MoTaskbillDetailData genericDataItem1 = responseSaleData1.getData();
                    List<MaterialEntity> materialEntity = genericDataItem1.getMaterial_entity();
                    moTaskbillData.setMaterial_entity(materialEntity);
                    moTaskbillData.setCustom_field(genericDataItem1.getCustom_field());
                    moTaskbillData.setSrc_bill_no(genericDataItem1.getRemark());

                } else {
                    logger.error("查询生产任务单详情失败. Errcode: {}, Description: {}", responseSaleData1.getErrcode(), responseSaleData1.getDescription());
                    throw new RuntimeException(responseSaleData1.getErrcode() + ":" + responseSaleData1.getDescription());
                }
            }
        } catch (Exception ex) {
            logger.error("查询生产任务单：Error occurred while selecting sales taskill", ex);
            throw new RuntimeException(ex);
        }

        return moTaskBillRequestInsert;
    }

    /**
     * @MethodName putJXRaskOrder
     * @Parameters 生产任务单数据 未审核的数据推送敬信
     * @Author zhanghuiping
     * @Date 2025 - 05 - 06 02:02:17
     */
    public void putJXRaskOrder() {
        logger.info("单独获取生产任务单推送数据");
        // 1.查询生产任务单数据
        SalesOrderController controller = new SalesOrderController();
        List<MoTaskBillRequest> moTaskBillRequests = controller.selectTaskillOrder();
        if (moTaskBillRequests != null && moTaskBillRequests.size() > 0) {
            HttpUrlConnectionExample HttpExample = new HttpUrlConnectionExample();
            // 2.保存携带销售订单编号的生产任务单  生产任务单是 一个自制的的商品对应一个生产任务单
            for (MoTaskBillRequest moTaskBillRequest : moTaskBillRequests) {
                List<MoTaskBillRequest> auditTaskOrders = new ArrayList<>();
                List<putJXRaskbillDao> putJXRaskDaoList = new ArrayList<>();
                putJXRaskbillDao putJXRaskDao = new putJXRaskbillDao();
                putJXRaskDao.setTask_no(moTaskBillRequest.getBill_no());
                putJXRaskDao.setEmp(moTaskBillRequest.getEmp_name());
                putJXRaskDao.setTrans_type_id(moTaskBillRequest.getTrans_type_id());
                MaterialEntity materialEntity = moTaskBillRequest.getMaterial_entity().get(0);
                putJXRaskDao.setMaterialCode(materialEntity.getMaterial_number());//图令号
                putJXRaskDao.setMaterialName(materialEntity.getMaterial_name());
                putJXRaskDao.setMaterialNumber(String.valueOf(materialEntity.getQty()));//金蝶的id
                putJXRaskDao.setUnit(materialEntity.getUnit_name());
                putJXRaskDao.setPlan_commit_date(materialEntity.getPlan_commit_date());
                putJXRaskDao.setPlan_finish_date(materialEntity.getPlan_finish_date());
                putJXRaskDao.setOrder_no(moTaskBillRequest.getSrc_bill_no());
                //保存到销售订单的 自定义字段
                Map<String, String> CustFiled = moTaskBillRequest.getCustom_field();
                if (CustFiled != null) {
                    CustomFieldServiceImpl customFieldServiceImpl = new CustomFieldServiceImpl();
                    ResponseData<CustomFieldData> responseData1 = customFieldServiceImpl.selectMaterial(Constants.MO_TASK_BILL_TYPE);
                    String mapkey1 = "";
                    String mapkey2 = "";
                    if (responseData1.getErrcode() == 0) {
                        CustomFieldData customFieldData = responseData1.getData();
                        if (customFieldData != null) {
                            List<CustomField> head = customFieldData.getHead();
                            if (head.size() > 0) {
                                for (CustomField customField1 : head) {
                                    if ("项目名称".equals(customField1.getDisplay_name())) {
                                        mapkey1 = customField1.getNumber();
                                    }
                                    if ("交货日期".equals(customField1.getDisplay_name())) {
                                        mapkey2 = customField1.getNumber();
                                    }
                                }
                            }

                        }
                    }
                    //推送项目名称
                    if (mapkey1 != null && !mapkey1.equals("")) {
                        putJXRaskDao.setOrder_name(CustFiled.get(mapkey1));
                    }
                    //推送交货日期
                    if (mapkey2 != null && !mapkey2.equals("")) {
                        putJXRaskDao.setOrder_date(CustFiled.get(mapkey2));
                    }
                }


                putJXRaskDaoList.add(putJXRaskDao);
                logger.info("推送到敬信数据 putJXRaskDaoList: {}", gson.toJson(putJXRaskDaoList));
                String response = HttpExample.sendRequestApplyProduceOrder(gson.toJson(putJXRaskDaoList));
                if (response == null || "".equals(response)) {
                    logger.info("任务工单的-推送失败：再次推送");
                } else if (response.contains("集成成功")) {
                    logger.info("任务工单的-推送到敬信成功返回：response: {}", response);
                    // 3.保存成功审核一下 销售数据，下次不在查询
                    auditTaskOrders.add(moTaskBillRequest);
                    controller.auditTaskOrder(auditTaskOrders);
                } else {
                    logger.info("推送失败原因：response: {}", response);
                }
            }
        } else {
            logger.info("没有生产任务单推送数据");
        }
    }

    public static void main(String[] args) {
        SalesOrderController controller = new SalesOrderController();
        controller.insertRaskGetBySalesOrder();
//        List<SalesOrderData> listSales = controller.selectSalesOrder();
//        SalesOrderData salesOrderData = new SalesOrderData();
//        salesOrderData.setId("2192921674016380928");
//        listSales.add(salesOrderData);
//        controller.auditSaleOrder(listSales);
//        String response = "集成成功";
//        if (response == null || "".equals(response)) {
//            logger.info("销售订单时-生产任务单==》推送失败：再次推送");
//        } else if ("集成成功".equals(response.trim())) {
//            System.out.println('1');
//            logger.info("销售订单时-生产任务单==》推送到敬信成功返回：response: {}", response);
//            //保存成功审核一下 销售数据，下次不在查询Z
////            controller.auditTaskOrder(moTaskBillRequests);
//        } else {
//            logger.info("销售订单时-生产任务单==》1：再次推送");
//            logger.info("推送失败原因1：response: {}", response);
//        }

//        controller.insertRaskGetBySalesOrder();
//        controller.putJXRaskOrder();
    }

    /**
     * @return List<MoTaskbillDetailData> 未审核的生产任务单详情列表
     * @MethodName selectUnauditedTaskOrders
     * @Parameters 查询未审核的生产任务单详情列表
     * @Author zhanghuiping
     * @Date 2025-04-12
     */
    public List<MoTaskbillDetailData> selectUnauditedTaskOrders() {
        List<MoTaskbillDetailData> taskOrderDetails = new ArrayList<>();

        // 设置分页参数
        int page = 1;
        int pageSize = 10;
        map.put("page", String.valueOf(page));
        map.put("page_size", String.valueOf(pageSize));

        // 设置查询条件：未审核状态
        map.put("bill_status", "Z"); // 单据状态（Z表示未审核）

        try {
            ApiResult dataResult = Service.SelectDataList(Constants.MO_TASKBILL, map, "");

            Type dataType = new TypeToken<ResponseData<GenericDataItem<MoTaskbillData>>>() {
            }.getType();
            ResponseData<GenericDataItem<MoTaskbillData>> responseData = gson.fromJson(dataResult.getBody(), dataType);

            if (responseData.getErrcode() == 0) {
                GenericDataItem<MoTaskbillData> genericDataItem = responseData.getData();
                List<MoTaskbillData> dataList = genericDataItem.getRows();

                // 获取每个生产任务单的详细信息
                for (MoTaskbillData taskData : dataList) {
                    // 获取详细信息
                    HashMap<String, String> detailMap = new HashMap<>();
                    detailMap.put("id", taskData.getId());
                    detailMap.put("page", "1");
                    detailMap.put("page_size", "10");

                    ApiResult detailResult = Service.SelectDataDetail(Constants.MO_TASKBILL_DETAIL, detailMap, "");
                    Type detailType = new TypeToken<ResponseData<MoTaskbillDetailData>>() {
                    }.getType();
                    ResponseData<MoTaskbillDetailData> detailResponse = gson.fromJson(detailResult.getBody(), detailType);

                    if (detailResponse.getErrcode() == 0) {
                        MoTaskbillDetailData detailData = detailResponse.getData();
                        taskOrderDetails.add(detailData);
                    }
                }

                // 处理分页
                String count = genericDataItem.getCount();
                int totalCount = Integer.parseInt(count);
                int processedCount = pageSize;

                while (processedCount < totalCount) {
                    page++;
                    map.put("page", String.valueOf(page));

                    dataResult = Service.SelectDataList(Constants.MO_TASKBILL, map, "");
                    responseData = gson.fromJson(dataResult.getBody(), dataType);

                    if (responseData.getErrcode() == 0) {
                        genericDataItem = responseData.getData();
                        dataList = genericDataItem.getRows();

                        // 获取每个生产任务单的详细信息
                        for (MoTaskbillData taskData : dataList) {
                            // 获取详细信息
                            HashMap<String, String> detailMap = new HashMap<>();
                            detailMap.put("id", taskData.getId());
                            detailMap.put("page", "1");
                            detailMap.put("page_size", "10");

                            ApiResult detailResult = Service.SelectDataDetail(Constants.MO_TASKBILL_DETAIL, detailMap, "");
                            Type detailType = new TypeToken<ResponseData<MoTaskbillDetailData>>() {
                            }.getType();
                            ResponseData<MoTaskbillDetailData> detailResponse = gson.fromJson(detailResult.getBody(), detailType);

                            if (detailResponse.getErrcode() == 0) {
                                MoTaskbillDetailData detailData = detailResponse.getData();
                                taskOrderDetails.add(detailData);
                            }
                        }
                    }

                    processedCount = page * pageSize;
                }

                logger.info("查询到未审核的生产任务单详情数量: {}", taskOrderDetails.size());
            } else {
                logger.error("查询未审核生产任务单详情失败. Errcode: {}, Description: {}",
                        responseData.getErrcode(), responseData.getDescription());
            }
        } catch (Exception ex) {
            logger.error("查询未审核生产任务单详情时发生错误", ex);
            throw new RuntimeException("查询未审核生产任务单详情失败: " + ex.getMessage(), ex);
        }

        return taskOrderDetails;
    }
}